package com.easemob.helpdesk.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.easemob.helpdesk.EMValueCallBack;
import com.easemob.helpdesk.activity.AlertDialog;
import com.easemob.helpdesk.activity.PreviewWaitingSessionDialog;
import com.easemob.helpdesk.bean.SkillGroupBean;

import com.easemob.helpdesk.listener.OnDataItemClickListener;
import com.easemob.helpdesk.utils.PreferenceUtils;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;

//import com.easemob.helpdesk.activity.ScreeningActivity;
import com.easemob.helpdesk.activity.SearchWaitAccessActivity;
import com.easemob.helpdesk.adapter.WaitAccessAdapter;
import com.easemob.helpdesk.activity.MainActivity;

//import com.easemob.helpdesk.utils.AvatarManager;
import com.easemob.helpdesk.utils.OnFreshCallbackListener;
import com.easemob.helpdesk.utils.TimeInfo;
import com.easemob.helpdesk.widget.recyclerview.DividerLine;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.TechChannel;
import com.hyphenate.kefusdk.chat.HDClient;
//import com.hyphenate.kefusdk.entity.HDUser;
//import com.hyphenate.kefusdk.entity.WaitAccessScreenEntity;
import com.hyphenate.kefusdk.entity.user.HDUser;
import com.hyphenate.kefusdk.entity.user.HDVisitorUser;
import com.hyphenate.kefusdk.gsonmodel.main.SkillGroupResponse;
import com.hyphenate.kefusdk.gsonmodel.main.WaitQueueResponse;
import com.hyphenate.kefusdk.manager.main.WaitAccessManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.net.ApiService;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import retrofit2.Call;

/**
 * 待接入页面
 */
public class WaitAccessFragment extends Fragment implements OnFreshCallbackListener, SwipeRefreshLayout.OnRefreshListener{

    private static final String TAG = WaitAccessFragment.class.getSimpleName();

    private static final int MSG_LOAD_MORE_DATA = 0x01;
    private static final int MSG_REFRESH_DATA = 0x02;
    private static final int MSG_AUTHENTICATION = 0x03;
    public static final int REQUEST_CODE_PREVIEW_WAITTING_SESSION = 0x04;
    private static final int REQUEST_CODE_SCREENING = 0x05;
    private static final int REQUEST_CODE_SEARCH = 0x06;
    public static final int REQUEST_CODE_ALERT_DIALOG_TRANSFER = 0x07;
    public static final int REQUEST_CODE_ALERT_DIALOG_CLOSE = 0x08;

    private List<WaitQueueResponse.ItemsBean> waitUsersList = Collections.synchronizedList(new ArrayList<WaitQueueResponse.ItemsBean>());


    public EasyRecyclerView recyclerView;
    private ProgressDialog pd = null;
    private WaitAccessAdapter adapter;
    private WeakHandler mWeakHandler;

    private EMValueCallBack emCallBack;

    public static OnFreshCallbackListener callback = null;
    private static final int PER_PAGE_WAIT_COUNT = 20;

//    @BindView(R.id.iv_avatar)
//    public ImageView ivAvatar;
//    @BindView(R.id.iv_status)
//    public ImageView ivStatus;
//    @BindView(R.id.iv_filter)
//    public View ibtnFilter;
private  void initFindView(View view){
    recyclerView=view.findViewById(R.id.recyclerView);
    tvLabelTotalCount=view.findViewById(R.id.tv_label_total_count);
    search_layout=view.findViewById(R.id.search_layout);
}
    public TextView tvLabelTotalCount;

    public RelativeLayout search_layout;
    private boolean isSearch;
    private List<SkillGroupResponse.EntitiesBean> agentList = Collections.synchronizedList(new ArrayList<SkillGroupResponse.EntitiesBean>());
    private WaitAccessManager waitAccessManager;
    private int mCurPageNo;
    private TimeInfo currentTimeInfo = new TimeInfo();
    private WaitQueueResponse.ItemsBean mSelectSession;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait, container, false);
        initFindView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        callback = this;
        mWeakHandler = new WeakHandler(this);
        waitAccessManager = new WaitAccessManager();
        setUpView();
    }

    private void setUpView() {
//        ibtnFilter.setOnClickListener(new OnFilterClickListener());
        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        //设置分割线
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(1);
        dividerLine.setColor(0xFFDDDDDD);
        recyclerView.addItemDecoration(dividerLine);

        recyclerView.getSwipeToRefresh().setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark, R.color.holo_orange_light, R.color.holo_red_light);
        adapter = new WaitAccessAdapter(getActivity());
        recyclerView.setAdapterWithProgress(adapter);
        adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreData();
            }
        });
//        adapter.setNoMore(R.layout.view_nomore);
        adapter.setError(R.layout.view_error).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.resumeMore();
            }
        });

        isSearch = true;
        recyclerView.setRefreshListener(this);
        adapter.addAll(waitUsersList);
        if (agentList == null || agentList.isEmpty()){
            loadSkillGroups();
        }else{
            loadTheFirstPageData();
        }

        loadFirstStatus();
        refreshAgentAvatar();

        search_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(waitUsersList == null || waitUsersList.size() == 0){
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getActivity(), SearchWaitAccessActivity.class);
                intent.putExtra("list", (Serializable) waitUsersList);
                startActivityForResult(intent, REQUEST_CODE_SEARCH);
            }
        });

//        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int i) {
//
//                if(getContext() instanceof MainActivity){
//                    ((MainActivity)getContext()).getMsgFragment().waitIntent(i, 1);
//                }else if (getContext() instanceof SearchWaitAccessActivity){
//                    ((SearchWaitAccessActivity)getContext()).clickAccess(i, 1);
//                }
//
//            }
//        });

        adapter.setOnDataItemClickListener(new OnDataItemClickListener<WaitQueueResponse.ItemsBean>() {
            @Override
            public void onClick(View itemView, WaitQueueResponse.ItemsBean data) {
                boolean isOpenPreviewMessage = PreferenceUtils.getInstance().getOpenPreviewMsgStatus();
                if (isOpenPreviewMessage){
                    previewSession(data);
                }else {
                    receptionSession(data);
                }
                Log.d(TAG, "onClick: ");
            }
        });

    }

    //预览
    private void previewSession(WaitQueueResponse.ItemsBean data){
        mSelectSession = data;
        String sessionId = data.getSessionId();

        HDVisitorUser toUser = new HDVisitorUser();
        toUser.setUserId(data.getVisitorId());
        toUser.setUsername(data.getVisitorName());
        toUser.setNicename(data.getVisitorName());
        Intent intent = new Intent();
        intent.setClass(getContext(), PreviewWaitingSessionDialog.class);
        intent.putExtra("user", toUser);
        intent.putExtra("visitorid", sessionId);
        intent.putExtra("originType", data.getOriginType());
        intent.putExtra("techChannelName", data.getChanneName());
        startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
    }



    //询问直接接入
    private void receptionSession(WaitQueueResponse.ItemsBean data){
        mSelectSession = data;
        Intent intent = new Intent(getActivity(), AlertDialog.class);
        intent.putExtra("position", 1);
        intent.putExtra("msg", "您确认要接待此会话吗？");
        intent.putExtra("okString", "确认");
        startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
    }


//    public void clickAccess(int position, int index){
//        if (index == 1){
//            Intent intent = new Intent(getActivity(), AlertDialog.class);
//            intent.putExtra("position", position);
//            intent.putExtra("msg", "您确认要接待此会话吗？");
//            intent.putExtra("okString", "确认");
//            startActivityForResult(intent, REQUEST_CODE_PREVIEW_WAITTING_SESSION);
//        }else if (index == 2){
//            startActivityForResult(new Intent(getActivity(), TransferActivity.class).putExtra("position", position), REQUEST_CODE_ALERT_DIALOG_TRANSFER);
//        }else if (index == 3){
//            //waitAbort
//            Intent intent = new Intent(getActivity(), AlertDialog.class);
//            intent.putExtra("position", position);
//            intent.putExtra("msg", "您确认要关闭此会话吗？");
//            intent.putExtra("okString", "确认");
//            startActivityForResult(intent, REQUEST_CODE_ALERT_DIALOG_CLOSE);
//        }
//
//    }


    public void refreshLabelTotalCount(int count) {
//        if (tvLabelTotalCount != null) {
//            tvLabelTotalCount.setText("当前筛选结果 " + count + " (共 " + waitAccessManager.getTotal_count() + ")");
//        }
    }

    private void loadFirstStatus() {
        HDUser loginUser = HDClient.getInstance().getCurrentUser();
        if (loginUser != null) {
            refreshOnline(loginUser.getOnLineState());
        }
    }

    public void refreshOnline(String status) {
//        CommonUtils.setAgentStatusView(ivStatus, status);
    }

    public void refreshAgentAvatar() {
//        if(ivAvatar != null)
//            AvatarManager.getInstance(getContext()).refreshAgentAvatar(getActivity(), ivAvatar);
    }

    @Override
    public void onRefresh() {
        if (agentList == null || agentList.isEmpty()){
            loadSkillGroups();
        }else{
            loadTheFirstPageData();
        }
//        loadTheFirstPageData();
    }

    @Override
    public void onFresh(EMValueCallBack callback) {
//        refreshSessionLabel();
        emCallBack = callback;
        onRefresh();

    }

//    private void refreshSessionLabel() {
//        int waitCount = waitAccessManager.getTotal_count();
//        ((MainActivity) getActivity()).refreshSessionUnreadCount(waitCount);
//    }

//    public void waitCloseActivityResult(final WaitQueueResponse.ItemsBean data){
////        final int position = data.getIntExtra("position", -1);
////        if (position == -1) {
////            return;
////        }
////
////        if(position >= adapter.getCount()){
////            return;
////        }
////
//        if (pd == null) {
//            pd = new ProgressDialog(getActivity());
//        }
//        pd.setMessage("关闭中...");
//        pd.show();
//
////        final WaitQueueResponse.ItemsBean bean = adapter.getItem(position);
//
//        waitAccessManager.waitAbort(data, new HDDataCallBack<String>() {
//            @Override
//            public void onSuccess(String value) {
//                if (getActivity() == null) {
//                    return;
//                }
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        closeDialog();
//                        adapter.remove(data);
//                        updateListCount();
//                    }
//                });
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                if (getActivity() == null) {
//                    return;
//                }
//                (getActivity()).runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        closeDialog();
//                        Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//
//            @Override
//            public void onAuthenticationException() {
//                if (getActivity() == null) {
//                    return;
//                }
//                (getActivity()).runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        closeDialog();
//                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");
//                    }
//                });
//            }
//        });
//    }

    public void transferActivityResult(final WaitQueueResponse.ItemsBean item,String userId){
//        String userId = data.getStringExtra("userId");
//        long queueId = data.getLongExtra("queueId", 0);

        showLoading("转接中...");


        waitAccessManager.transferWaitAccess(item, userId, 0, new HDDataCallBack<String>() {
            @Override
            public void onSuccess(String value) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeDialog();
                        adapter.remove(item);
                        updateListCount();
                    }
                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (getActivity() == null) {
                    return;
                }
                (getActivity()).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        closeDialog();
                        Toast.makeText(getActivity(), "转接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onAuthenticationException() {
                if (getActivity() == null) {
                    return;
                }
                (getActivity()).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        closeDialog();
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");
                    }
                });
            }
        });
    }

    private void showLoading(String message) {
        if (pd == null) {
            pd = new ProgressDialog(getActivity());
        }
        pd.setMessage(message);
        pd.show();
    }

    public void closeDialog(){
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }

    public void waitAccessActivityResult(final WaitQueueResponse.ItemsBean data){
//        final int position = data.getIntExtra("position", -1);
//        if (position == -1) {
//            return;
//        }
//        if(position >= adapter.getCount()){
//            return;
//        }
        showLoading("接入中...");

//        final WaitQueueResponse.ItemsBean bean = adapter.getItem(position);

        waitAccessManager.accessWaitUser(data.getSessionId(), new HDDataCallBack<String>() {

            @Override
            public void onSuccess(String value) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeDialog();
                        adapter.remove(data);
                        updateListCount();
                        ((MainActivity) getActivity()).getMsgFragment().selectTopTab(1);
                    }
                });
            }

            @Override
            public void onError(int error, String errorMsg) {
                HDLog.e(TAG, "errorMsg:" + errorMsg);
                if (getActivity() == null) {
                    return;
                }
                (getActivity()).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        closeDialog();
                        Toast.makeText(getActivity(), "接入失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onAuthenticationException() {
                if (getActivity() == null) {
                    return;
                }
                (getActivity()).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        closeDialog();
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");
                    }
                });
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            if(requestCode == REQUEST_CODE_SEARCH){
                final WaitQueueResponse.ItemsBean entity = (WaitQueueResponse.ItemsBean) data.getSerializableExtra("entty");
//                int pos = -1;
//                for (int i = 0; i < waitUsersList.size(); i++) {
//                    if(waitUsersList.get(i).getVisitorName().equals(entity.getVisitorName())){
//                        pos = i;
//                        break;
//                    }
//                }
//                if (pos == -1) {
//                    return;
//                }
//                if (pos >= adapter.getCount()) {
//                    return;
//                }
//
//                int index = data.getIntExtra("index", 0);
//                final int position = pos;
//                if (index == 1){
                boolean isTransfer = data.getBooleanExtra("isTransfer", false);
                if (isTransfer){
                    String userId = data.getStringExtra("userId");
                    transferActivityResult(entity,userId);
                }else {
                    waitAccessActivityResult(entity);
                }
//                    if (pd == null) {
//                        pd = new ProgressDialog(getActivity());
//                        pd.setMessage("接入中...");
//                    }
//                    pd.show();
//
////                    final WaitQueueResponse.ItemsBean bean = adapter.getItem(position);
//
//                    waitAccessManager.accessWaitUser(entity.getSessionId(), new HDDataCallBack<String>() {
//
//                        @Override
//                        public void onSuccess(String value) {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            getActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    adapter.remove(entity);
//                                    updateListCount();
//                                    ((MainActivity) getActivity()).getMsgFragment().selectTopTab(1);
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onError(int error, String errorMsg) {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            (getActivity()).runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    Toast.makeText(getActivity(), "接入失败", Toast.LENGTH_SHORT).show();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onAuthenticationException() {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            (getActivity()).runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    MainApplication.getInstance().getEventEmitter().sendEvent("logout");
//                                }
//                            });
//                        }
//                    });

//                }else if (index == 2){
//                    transferActivityResult(data, position);
//                }else if (index == 3){
//                    if (pd == null) {
//                        pd = new ProgressDialog(getActivity());
//                    }
//                    pd.setMessage("关闭中...");
//                    pd.show();
//
////                    final WaitQueueResponse.ItemsBean bean = adapter.getItem(position);
//
//                    waitAccessManager.waitAbort(entity, new HDDataCallBack<String>() {
//                        @Override
//                        public void onSuccess(String value) {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            getActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    adapter.remove(entity);
//                                    updateListCount();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onError(int error, String errorMsg) {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            (getActivity()).runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onAuthenticationException() {
//                            if (getActivity() == null) {
//                                return;
//                            }
//                            (getActivity()).runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    closeDialog();
//                                    MainApplication.getInstance().getEventEmitter().sendEvent("logout");
//                                }
//                            });
//                        }
//                    });
//
//                }


            }else if(requestCode == REQUEST_CODE_PREVIEW_WAITTING_SESSION){
                boolean isTransfer = data.getBooleanExtra("isTransfer", false);
                if (isTransfer){
                    String userId = data.getStringExtra("userId");
                    transferActivityResult(mSelectSession,userId);
                }else {
                    waitAccessActivityResult(mSelectSession);
                }
            }
//            else if(requestCode == REQUEST_CODE_ALERT_DIALOG_TRANSFER){
//                final int position = data.getIntExtra("position", -1);
//                transferActivityResult(data);
//            }
//            else if(requestCode == REQUEST_CODE_ALERT_DIALOG_CLOSE){
//                waitCloseActivityResult(mSelectSession);
//            }
//            else if(requestCode == REQUEST_CODE_SCREENING){
//                WaitAccessScreenEntity screenEntity = new WaitAccessScreenEntity();
//                currentTimeInfo = (TimeInfo) data.getSerializableExtra("timeinfo");
//                screenEntity.startTime = currentTimeInfo.getStartTime();
//                screenEntity.endTime = currentTimeInfo.getEndTime();
//                if(data.hasExtra("originType")){
//                    screenEntity.currentOriginType = data.getStringExtra("originType");
//                }
//                if(data.hasExtra("techChannel")){
//                    screenEntity.currentTechChannel = (TechChannel) data.getSerializableExtra("techChannel");
//                }
//                if(data.hasExtra("visitorName")){
//                    screenEntity.currentVisitorName = data.getStringExtra("visitorName");
//                }
//                waitAccessManager.setScreeningOption(screenEntity);
//                isSearch = true;
//                onFresh(null);
//            }

        }

    }

    private static class WeakHandler extends Handler {
        WeakReference<WaitAccessFragment> weakReference;

        public WeakHandler(WaitAccessFragment fragment) {
            this.weakReference = new WeakReference<WaitAccessFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            WaitAccessFragment fragment = weakReference.get();
            if (null != fragment) {
                switch (msg.what) {
                    case MSG_LOAD_MORE_DATA:
                        fragment.updateView((List<WaitQueueResponse.ItemsBean>) msg.obj);
                        break;
                    case MSG_REFRESH_DATA:
                        fragment.refreshView((List<WaitQueueResponse.ItemsBean>) msg.obj);
                        break;
                    case MSG_AUTHENTICATION:
                        MainApplication.getInstance().getEventEmitter().sendEvent("logout");
                        break;
                    default:
                        break;
                }
            }


        }
    }

    @Override
    public void onDestroy() {
        mWeakHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
        callback = null;
    }

    private void updateView(List<WaitQueueResponse.ItemsBean> data) {
        if (data != null && adapter != null) {
            if (data.size() == 0) {
                adapter.stopMore();
                return;
            }
            adapter.addAll(data);
            waitUsersList.addAll(data);
            adapter.notifyDataSetChanged();
            updateListCount();
            refreshLabelTotalCount(adapter.getCount());
            adapter.pauseMore();
        } else {
            if (recyclerView != null) {
                recyclerView.setRefreshing(false);
            }
        }

    }

    private void refreshView(List<WaitQueueResponse.ItemsBean> data) {
        if (data != null && adapter != null) {
            adapter.clear();
            waitUsersList.clear();
            waitUsersList.addAll(data);
            adapter.addAll(data);
            adapter.notifyDataSetChanged();
            refreshLabelTotalCount(adapter.getCount());
            if (data.size() < PER_PAGE_WAIT_COUNT) {
                adapter.stopMore();
            }
            updateListCount();
            adapter.pauseMore();

            if(emCallBack != null){
                emCallBack.onSuccess(((MainActivity) getActivity()).getMsgFragment().waitCount);
            }

        } else{
            if (recyclerView != null) {
                recyclerView.setRefreshing(false);
            }
        }

    }

    private void loadMoreData() {
        waitAccessManager.getUserWaitQueues(isSearch, agentList, mCurPageNo + 1, new HDDataCallBack<List<WaitQueueResponse.ItemsBean>>() {
            @Override
            public void onSuccess(List<WaitQueueResponse.ItemsBean> value) {
                if (getActivity() == null) {
                    return;
                }
                mCurPageNo++;
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_LOAD_MORE_DATA;
                message.obj = value;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (getActivity() == null) {
                    return;
                }
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_LOAD_MORE_DATA;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onAuthenticationException() {
                if (getActivity() == null) {
                    return;
                }
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_AUTHENTICATION;
                mWeakHandler.sendMessage(message);
            }
        });
    }

    private void updateListCount() {
        if (getActivity() != null) {
            ((MainActivity) getActivity()).getMsgFragment().refreshWaitUnreadCount();
        }
    }

    private synchronized void loadSkillGroups(){
        if (TextUtils.isEmpty(MainActivity.mSkillGroup)){
            ApiService apiService = HKHttpUtils.getApiService();
            apiService.getSkillGroup(MainActivity.ticket).enqueue(new HKResponseResultCallBack<SkillGroupBean>() {
                @Override
                public void onSuccess(SkillGroupBean skillGroupBean) {
                    if (skillGroupBean != null && !TextUtils.isEmpty(skillGroupBean.getGroup())){
                        MainActivity.mSkillGroup = skillGroupBean.getGroup();
                        realLoadSkillGroup(MainActivity.mSkillGroup);
                    }else{
                        Toast.makeText(getActivity(),"请求失败：获取技能组失败",Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onGetDataFailed(int cd, String msg) {
                    Toast.makeText(getActivity(),"请求失败："+msg,Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailed(Call call, Throwable t) {
                    Toast.makeText(getActivity(),"请求失败",Toast.LENGTH_LONG).show();
                }
            });
        }else{
            realLoadSkillGroup(MainActivity.mSkillGroup);
        }



    }

    private void realLoadSkillGroup(final String skillGroup){
        waitAccessManager.loadSkillGroup(new HDDataCallBack<List<SkillGroupResponse.EntitiesBean>>() {
            @Override
            public void onSuccess(List<SkillGroupResponse.EntitiesBean> value) {
                agentList.clear();
                for (int i = 0; i < value.size(); i++) {
                    if(value.get(i).getQueueName().equals(skillGroup)){
                        agentList.add(value.get(i));
                    }
                }

//                if(agentList.size()> 0){
//                    HDNotifier.getInstance().notifiNewMsg();
//                }

                loadTheFirstPageData();
            }

            @Override
            public void onError(int error, String errorMsg) {
                HDLog.e(TAG, "asyncGetSkillGroups-onError:" + errorMsg);
            }

            @Override
            public void onAuthenticationException() {
            }
        });
    }

    private synchronized void loadTheFirstPageData() {
//        waitAccessManager.setPageCount(1000);
        waitAccessManager.getUserWaitQueues(isSearch, agentList, 0, new HDDataCallBack<List<WaitQueueResponse.ItemsBean>>() {
            @Override
            public void onSuccess(List<WaitQueueResponse.ItemsBean> value) {
                if (getActivity() == null) {
                    return;
                }
                mCurPageNo = 1;
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_REFRESH_DATA;
                message.obj = value;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (getActivity() == null) {
                    return;
                }
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_REFRESH_DATA;
                mWeakHandler.sendMessage(message);
            }

            @Override
            public void onAuthenticationException() {
                if (getActivity() == null) {
                    return;
                }
                Message message = mWeakHandler.obtainMessage();
                message.what = MSG_AUTHENTICATION;
                mWeakHandler.sendMessage(message);
            }
        });

    }

    public int getWaitTotalCount() {
        if (waitAccessManager != null) {
            return waitAccessManager.getTotal_count();
        }
        return 0;
    }

    class OnFilterClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            //Intent intent = new Intent();
            //intent.setClass(getActivity(), ScreeningActivity.class);
            //intent.putExtra("timeinfo", currentTimeInfo);
            //startActivityForResult(intent, REQUEST_CODE_SCREENING);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        callback = null;
        adapter = null;
    }


}
